﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using GrewalCRM.Entities.Common;
using GrewalCRM.Entities;
using GrewalCRM.DAL;
using System.Data;
using System.Web;
using System.IO;
using System.Net;

namespace GrewalCRM.BLL
{
  public class CallLog_BLL : BaseBLLGrewalCRM, IBaseBLLGrewalCRM
  {
    public CallLog_BLL()
    {
      baseDAL = new CallLog_DAL();
    }

    private CallLog_DAL callLogDAL
    {
      get { return baseDAL as CallLog_DAL; }
    }




    #region Public Methods    
    public List<CallLog> GetAllCallsByCondition(int? Month,int? CallStatusID, string ZipCode)
    {
      List<CallLog> calls = new List<CallLog>();      
      calls = callLogDAL.GetAllByCndition(Month, CallStatusID, ZipCode);
      return calls;
    }
    public List<CallLog> GetAllCallsByAdvanceSearch(SearchCriteria criteria)
    {
      List<CallLog> calls = new List<CallLog>();      
      calls = callLogDAL.GetAllCallsByAdvanceSearch(criteria);
      return calls;
    }
    public List<ReportInstallationSummary> GetInstallationSummaryCashTransationReportMonthly(DateTime? FromDate, DateTime? ToDate, int? CallTypeID, int? DealerID, int? CallStatusID, int? InstallerID)
    {
      List<ReportInstallationSummary> rpt = new List<ReportInstallationSummary>();
      rpt = callLogDAL.GetInstallationSummaryCashTransationReportMonthly(FromDate, ToDate, CallTypeID, DealerID, CallStatusID, InstallerID);
      return rpt;
    }
    public CallLog GetCallsByID(int ID)
    {
        return (GetByID(ID)) as CallLog;
    }
    public int Save(BaseEntitiesGrewalCRM Entity)
    {
      int result = 0;
      EntityState state = EntityState.Nutral;

      if (Entity.ID == 0)
        state = EntityState.New;
      else if (Entity.IsChanged)
        state = EntityState.Changed;
      else if (Entity.IsMarkedDeleted)
        state = EntityState.Deleted;

      switch (state)
      {
        case EntityState.New:
          result = AddNew(Entity);
          break;
        case EntityState.Changed:
          result = Update(Entity);
          break;
        case EntityState.Deleted:
          break;
        default:
          result = 0;
          break;

      }

      return result;

    }
    #endregion

    #region Protected Methods
    
    protected override int AddNew(BaseEntitiesGrewalCRM Entity)
    {
      return baseDAL.AddNew(Entity);
    }

    protected override int Update(BaseEntitiesGrewalCRM Entity)
    {
        CallLog savedCall = GetCallsByID(Entity.ID);

        int result = baseDAL.Update(Entity);

        CallLog call = null;
        call = (Entity as CallLog);

        

        try
        {
            if (call.CallStatus.ID == (int)CallStatus.Assigned && call.Installer.ID > 0 && call.Installer.ID != savedCall.Installer.ID )
            {
                string isSMSEnabled = null;

                isSMSEnabled = ConfigurationManager.AppSettings["IS_SMS_ENEBLED"].ToString() ?? null;

                if (isSMSEnabled == "1")
                {
                    string smsUID = null;
                    string smsPWD = null;
                    string smsSenderID = null;
                    string smsAPIURLTemplate = "http://smsc.biz/httpapi/send?username={0}&password={1}&sender_id={2}&route=T&phonenumber={3}&message={4}";
                    string smsDeliveryStatusTemplate = "http://smsc.biz/api/smsdlr?username={0}&password={1}&phonenumber={2}&broadcastid={3}&date={4}";
                    string smsAPIURL = null;
                    string smsSendResponse = null;
                    string smsSentDate = DateTime.Now.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
                    string smsToBeSend = null;
                    bool isDeliveredSucessfully;

                    WebClient client = new WebClient();

                    InstallersMaster_BLL tempInstallerBLL = new InstallersMaster_BLL();
                    tempInstallerBLL.FillInstaller(call.Installer);

                    ACBrands_BLL acBrandBLL = new ACBrands_BLL();
                    acBrandBLL.FillACBrand(call.ACBrand);


                    smsUID = ConfigurationManager.AppSettings["SMS_USER_ID"];
                    if (smsUID != null)
                        smsUID = smsUID.ToString();

                    smsPWD = ConfigurationManager.AppSettings["SMS_PWD"];
                    if (smsPWD != null)
                        smsPWD = smsPWD.ToString();


                    smsSenderID = ConfigurationManager.AppSettings["SMS_SENDER_ID"];
                    if (smsSenderID != null)
                        smsSenderID = smsSenderID.ToString();
                        
                       
                    //Sending SMS to Customer
                    smsToBeSend = prepareCustomerSMS(smsUID, smsPWD, smsSenderID, call);
                    if (smsToBeSend != null)
                    {
                        smsAPIURL = string.Format(smsAPIURLTemplate, smsUID, smsPWD, smsSenderID, call.Customer.MobileNo1, smsToBeSend);
                        smsSendResponse = client.DownloadString(smsAPIURL);
                    }

                    isDeliveredSucessfully = isDelivered(client, smsUID, smsPWD, call.Customer.MobileNo1, ref smsSendResponse, smsSentDate, smsDeliveryStatusTemplate);

                    if (!isDeliveredSucessfully)
                        logFailedSMS(call.ID, DateTime.Now, "Customer", call.Customer.CustomerName, call.Customer.MobileNo1, smsToBeSend, smsSendResponse);

                    //Sending SMS to Installer
                    smsToBeSend = prepareInstallerSMS(smsUID, smsPWD, smsSenderID, call);
                    if (smsToBeSend != null)
                    {
                        smsAPIURL = string.Format(smsAPIURLTemplate, smsUID, smsPWD, smsSenderID, call.Installer.MobileNo, smsToBeSend);
                        smsSendResponse = client.DownloadString(smsAPIURL);
                    }

                    isDeliveredSucessfully = isDelivered(client, smsUID, smsPWD, call.Installer.MobileNo, ref smsSendResponse, smsSentDate, smsDeliveryStatusTemplate);

                    if (!isDeliveredSucessfully)
                        logFailedSMS(call.ID, DateTime.Now, "Installer", call.Installer.InstallerName, call.Installer.MobileNo, smsToBeSend, smsSendResponse);
                }
            }
        }
        catch (Exception ex)
        {
            string message = ex.Message;
            logFailedSMS(call.ID, DateTime.Now, "exception", call.Customer.CustomerName + " / " + call.Installer.InstallerName, call.Customer.MobileNo1 + " / " + call.Installer.MobileNo, message, "Both Failed");
        }
        return result;
    }

    private string prepareCustomerSMS(string smsUID, string smsPWD, string smsSenderID,  CallLog call)
    {
        string customerMsg = null;
        if (smsUID != null && smsPWD != null && smsSenderID != null)
        {
            customerMsg = ConfigurationManager.AppSettings["SMS_TEMPLATE_CUSTOMER"];
            if (customerMsg != null)
                customerMsg = customerMsg.ToString();
            if (customerMsg != null)
            {
                customerMsg = string.Format(customerMsg, call.Customer.CustomerName, call.ID.ToString(), call.Installer.InstallerName, call.Installer.MobileNo);
                customerMsg = HttpUtility.UrlEncode(customerMsg);
            }
        }
        return customerMsg;       
    }

    private string prepareInstallerSMS(string smsUID, string smsPWD, string smsSenderID, CallLog call)
    {
        string installerMsg = null;
        string customerContact = null;
        if (smsUID != null && smsPWD != null && smsSenderID != null)
        {
            installerMsg = ConfigurationManager.AppSettings["SMS_TEMPLATE_INSTALLER"];
            if (installerMsg != null)
                installerMsg = installerMsg.ToString();
            if (installerMsg != null)
            {
                customerContact = (call.Customer.MobileNo1 != null ? call.Customer.MobileNo1.Trim() : string.Empty) + ", " +
                    (call.Customer.PhoneNo != null ? call.Customer.PhoneNo.Trim() : string.Empty) + ", " +
                    (call.Customer.MobileNo2 != null ? call.Customer.MobileNo2.Trim() : string.Empty);

                installerMsg = string.Format(installerMsg, call.Customer.CustomerName, call.Customer.MobileNo1, call.Customer.Address, call.Customer.ZipCode, call.ACBrand.ACBrandName, call.ACModelNo);
                installerMsg = HttpUtility.UrlEncode(installerMsg);
            }
        }
        return installerMsg;
    }

    private bool isDelivered (WebClient client, string smsUID, string smsPWD, string smsSentToMobileNo, ref string smsSentMessageID, string smsSentDate, string smsDeliveryStatusTemplate)
    {
        if (smsSentMessageID == null)
            return false;

        bool isDelivered = true;
        string smsDeliveryStatus = null;
        string smsAPIURL = null;        
        
        if (smsSentMessageID[0] != '-')
        {
            smsAPIURL = string.Format(smsDeliveryStatusTemplate, smsUID, smsPWD, smsSentToMobileNo, smsSentMessageID, smsSentDate);

            smsDeliveryStatus = client.DownloadString(smsAPIURL);

            if (smsDeliveryStatus[0] != '-' && smsDeliveryStatus.ToUpper() == "FAILED")
            {
                isDelivered = false;               
            }
            else if (smsDeliveryStatus[0] == '-')
            {
                isDelivered = false;  
            }
        }
        else if (smsSentMessageID[0] == '-')
        {
            isDelivered = false;            
        }
        
        return isDelivered;        
    }

    private int logFailedSMS(int callID, DateTime sendDate, string SMSrecipientType, string SMSrecipientName, string SMSrecipientMobileNo, string smsMsg, string smsSendResponse)
    {
        int result;
        smsSendResponse = smsSendResponse != null ? smsSendResponse : "Message Template or User Credential or Sender ID Not Found";
        SMSFailure_BLL smsFailureBLL = new SMSFailure_BLL();
        SMSFailure failedSMS = new SMSFailure(callID, sendDate, SMSrecipientType, SMSrecipientName, SMSrecipientMobileNo, smsMsg, smsSendResponse);
        result = smsFailureBLL.Save(failedSMS);  
        return result;
    }

    protected override int Delete(BaseEntitiesGrewalCRM Entity)
    {
      throw new NotImplementedException();
    } 

    protected override List<BaseEntitiesGrewalCRM> GetAll()
    {
      return baseDAL.GetAll();
    }

    protected override BaseEntitiesGrewalCRM GetByID(int ID)
    {
        return baseDAL.GetByID(ID);
    }

    protected override void FillEntity(BaseEntitiesGrewalCRM Entity)
    {
      throw new NotImplementedException();
    } 
    #endregion

    #region Private Methods
    public string sendSMS(string toMobileNo, string message)
    {

        string sUserID = "somesh21jul";
        string sPwd = "J2eenet!";
        string sNumber = toMobileNo;
        string sSID = "WEBSMS";
        string sMessage = message;
        string sURL = "http://api.smsgatewayhub.com/smsapi/pushsms.aspx?user=" + sUserID + "&pwd=" + sPwd + "&to=" + sNumber + "&sid=" + sSID + "&msg=" + sMessage + "&fl=0&gwid=2";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sURL);
        request.MaximumAutomaticRedirections = 4;
        request.Credentials = CredentialCache.DefaultCredentials;
        try
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream receiveStream = response.GetResponseStream();
            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
            string sResponse = readStream.ReadToEnd();
            response.Close();
            readStream.Close();
            return sResponse;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

    private string sendSMS1(string toMobileNo, string message)
    {
        string sUserID = "demouser";
        string sPwd = "1303046044";
        string sNumber = toMobileNo;
        string sSID = "ONLINE";
        string sMessage = message;
        string baseurl = "http://bulksms.mysmsmantra.com:8080/WebSMS/SMSAPI.jsp?username=" + sUserID + "&password=" + sPwd + "&sendername=" + sSID + "&mobileno=91" + toMobileNo + "&message=MySMSMantra-" + message;

        WebClient client = new WebClient();
        
        Stream data = client.OpenRead(baseurl);
        StreamReader reader = new StreamReader(data);
        string sResponse = reader.ReadToEnd();
        data.Close();
        reader.Close();
        return sResponse;
    }

    #endregion
  }
}
